<?php
/*
 * author:pipistrll
 * email:appyouxiang@163.com
 */
class ListArtController extends CController {
    public $row = 10;
    public $page = 1;
    public $total = 0;
    public $ordering = 'asc';
    public $isType = 0;
    public $isSmallType = 0;
    public $totalPage = 0;
    public $layout='application.admin.views.layouts.main';
    public function filters() {
        return array(
            array(
                'application.admin.filters.MemcheckFilter'
            )
        );
    }

    public function actionIndex(){

        if(isset($_GET['row']) && !empty($_GET['row'])){
            $this->row = $_GET['row'];
            unset($_GET['row']);
        }
        if(isset($_GET['page'])&&!empty($_GET['page'])){
            $this->page = $_GET['page'];
            unset($_GET['page']);
        }
        if(isset($_GET['ordering']) && !empty($_GET['ordering'])){
            $this->ordering = $_GET['ordering'];
            unset($_GET['ordering']);
        }
        $this->isType = 5;
        $this->isSmallType = $_GET['isSmallType'];
        $_GET['arcrank'] = 1;
        $where = adminSys::_whereWork($_GET);
        $limit = ' limit '.($this->page-1)*$this->row.','.$this->row;
        $this->render('index',array(
            'data'=>$this->_getData($where,$limit),
            'channel'=>Channel::model()->findByPk($_GET['artTopId'])
        ));
    }
    public function actionMemberSet(){
        if(isset($_GET['row']) && !empty($_GET['row'])){
            $this->row = $_GET['row'];
            unset($_GET['row']);
        }
        if(isset($_GET['page'])&&!empty($_GET['page'])){
            $this->page = $_GET['page'];
            unset($_GET['page']);
        }
        if(isset($_GET['ordering']) && !empty($_GET['ordering'])){
            $this->ordering = $_GET['ordering'];
            unset($_GET['ordering']);
        }
        $this->isType = 4;
        $this->isSmallType = $_GET['isSmallType'];
        $_GET['midn'] = 1;
        $channelId = empty($_GET['channelid'])?'':$_GET['channelid'];
        $where = adminSys::_whereWork($_GET,'a.');
        $limit = ' limit '.($this->page-1)*$this->row.','.$this->row;
        $this->render('memberSet',array(
            'data'=>$this->_getMemData($where,$limit),
            'channel'=>Channel::model()->findAllByAttributes(array('Submission'=>1)),
            'channelId'=>$channelId
        ));
    }
    private function _getMemData($where,$limit=''){
        $sql = 'select a.*,c.typename from {{article}} as a '.
                'left join {{channel}} as c on a.channelId = c.id '.$where.' order by a.ordering '.$this->ordering.' '.$limit;
        $sql1 = 'select count(*) as count_num from {{article}} as a '.$where;
        $data = Yii::app()->db->createCommand($sql)->queryAll();
        $data1 = Yii::app()->db->createCommand($sql1)->queryRow();
        $this->total = $data1['count_num'];
        $this->totalPage = ceil($this->total/$this->row);
        return $data;
    }
    private function _getData($where,$limit=''){
        $sql = 'select * from {{article}} '.$where.' order by ordering '.$this->ordering.' '.$limit;
        $sql1 = 'select count(*) as count_num from {{article}} '.$where;
        $data = Yii::app()->db->createCommand($sql)->queryAll();
        $data1 = Yii::app()->db->createCommand($sql1)->queryRow();
        $this->total = $data1['count_num'];
        $this->totalPage = ceil($this->total/$this->row);
        return $data;
    }
     public function actionOrderingUp(){
      
       if(empty($_POST['strOrder']))return;
           $data = explode(',', $_POST['strOrder']);
            foreach($data as $key=>$value){
                Article::model()->updateByPk($value, array(
                    'ordering'=>(int)$_POST['ordering'][$key]
                ));
            }
        echo '<script>parent.reback(1);</script>';
   }
   public function actionEdit(){
       if(!isset($_GET['pkid'])||empty($_GET['pkid']))$this->redirect(array('listart/index'));
       
       $widget = Widget::model()->findByPk($_GET['wid']);
       if(empty($widget))$this->redirect(array('listart/index'));
       $addfileds = require_once 'addfileds_'.$widget->tableName.'.php';  
       $addCN = require_once 'addfiledsCn_'.$widget->tableName.'.php';
       $this->isSmallType = $_GET['channelId'];
       if(!empty($widget->Attribute)){
           $attributeArr = explode(',', $widget->Attribute);
           if(count($attributeArr) > 1){
               $attribute = '';
               foreach($attributeArr as $value){
                   $attribute .= ',';
                   $attribute .= 'd.'.$value;
               }
           }else{
               $attribute = ',d.'.$attributeArr[0];
           }
       }
       $sql = 'select a.id,a.channelId,a.title,a.keywords,a.description,a.click,a.Slitpic,a.litpic,a.flag,a.sourceURL,a.source,a.Awrite,a.senddate,a.ismobile,a.ordering,a.filetemp'.$attribute.' from {{article}} as a '.
           'left join {{add'.$widget->tableName.'}} as d on a.id = d.id where a.id = "'.$_GET['pkid'].'" ';
       $data = Yii::app()->db->createCommand($sql)->queryRow();
       $this->render('edit',array(
           'data'=>$data,
           'channel'=>Channel::model()->find('wid=:_wid',array(
               ':_wid'=>$widget->wid
           )),
           'attribute'=>$attributeArr,
           'addfileds'=>$addfileds,
           'modelName'=>$widget->tableName,
           'addCN'=>$addCN
       ));
   }
   public function actionAdd(){
       if(!isset($_GET['wid'])||empty($_GET['wid']))$this->redirect(array('listart/index'));
       $widget = Widget::model()->findByPk($_GET['wid']);
       if(!empty($widget->Attribute)){
           $attributeArr = explode(',', $widget->Attribute);

       }
       $this->isSmallType = $_GET['channelId'];
       $addfileds = require_once 'addfileds_'.$widget->tableName.'.php';  
       $addCN = require_once 'addfiledsCn_'.$widget->tableName.'.php';
        $this->render('add',array(
           'channelId'=>$_GET['channelId'],
            'wid'=>$_GET['wid'],
           'attribute'=>$attributeArr,
           'addfileds'=>$addfileds,
           'modelName'=>$widget->tableName,
           'addCN'=>$addCN,
           'filetemp'=>date('Ymd')
       ));
   }
   public function actionEditsave(){
       if(!IS_POST||!isset($_POST['pkid']))$this->redirect (array('listart/index'));
       if(empty($_POST['title'])){
           echo '<script>parent.showBack("标题不能为空！");</script>';
           return;
       }
       
       if($_POST['pkid']){
       $article = Article::model()->findByPk($_POST['pkid']);
       $add = "\$obj = Add".$_POST['modelName']."::model()->findByPk(".$_POST['pkid'].");";
       $article->Aupdate = time()-(8*3600);
       eval($add);
       }else{
           if(empty($_POST['wid']) || empty($_POST['channelId']) || empty($_POST['filetemp']))$this->redirect (array('site/error','msg'=>'参数错误，请与管理员联系！'));
           $article = new Article();
           $add = "\$obj = new Add".$_POST['modelName']."();";
           $article->senddate = time()-(8*3600);
           $article->wid = $_POST['wid'];
           $article->channelId = $_POST['channelId'];
           $article->channelIdAll = adminSys::_getAllId($_POST['channelId']);
           $article->filetemp = $_POST['filetemp'];
           $article->Awrite = $_POST['awrite'];
           $article->save();
           eval($add);
           $obj->id = $article->id;
           $obj->channelId = $article->channelId;
           $obj->userip = $_SERVER["REMOTE_ADDR"];
           $obj->save();
       }
       $addfileds = require_once 'addfileds_'.$_POST['modelName'].'.php';  
       if(!empty($_POST['title']) && $_POST['title'] != $article->title)$article->title = $_POST['title'];
       if($_POST['keywords'] != $article->keywords)$article->keywords = $_POST['keywords'];
       if(!empty($_POST['description']) && $_POST['description'] != $article->description)$article->description = $_POST['description'];
       if(!empty($_POST['ordering']) && $_POST['ordering'] != $article->ordering)$article->ordering = $_POST['ordering'];
       if(!empty($_POST['source']) && $_POST['source'] != $article->source)$article->source = $_POST['source'];
       if(!empty($_POST['sourceURL']) && $_POST['sourceURL'] != $article->sourceURL)$article->sourceURL = $_POST['sourceURL'];
       if(!empty($_POST['Awrite']) && $_POST['Awrite'] != $article->Awrite)$article->Awrite = $_POST['Awrite'];
       if($_POST['ismobile'] != 'undefined' && $_POST['ismobile'] != $article->ismobile)$article->ismobile = $_POST['ismobile'];
       if(!empty($_POST['flag']) && $_POST['flag'] != $article->flag)$article->flag = $_POST['flag'];
       if(!empty($_POST['litpic']) && $_POST['litpic'] != $article->litpic)$article->litpic = $_POST['litpic'];
       if(!empty($_POST['Slitpic']) && $_POST['Slitpic'] != $article->Slitpic)$article->Slitpic = $_POST['Slitpic'];
       if(isset($_POST['spicalModel']) && !empty($_POST['spicalModel'])){
        eval("\$this->_Edit".$_POST['spicalModel']."(&\$obj,\$addfileds);");   
       }else{
       foreach($addfileds as $key=>$value){
           if($value == 'date'){
           $obj->$key = adminSys::_time($_POST[$key], 2);   
           }else{
           $obj->$key = isset($_POST[$key])?$_POST[$key]:null;
           }
       }
       }
       if($_POST['modelName']=='vote'){
           $voteCount = 0;
           if(!empty($_POST['voteName'])){
               foreach($_POST['voteName'] as $k=>$v){
                   $lock = true;
                   if(empty($_POST['voteid'][$k])){
                   $vote = new Addvote_infos();
                   $vote->aid = $article->id;
                   $vote->count = 0;
                   $lock=false;
                   }else{
                       $vote = Addvote_infos::model()->findByPk($_POST['voteid'][$k]);
                   }
                   $vote->votename = $v;
                   $vote->litpic = $_POST['voteLitpic'][$k];
                   if(!$lock){
                   $vote->save();
                   }else{
                       if($_POST['voteCount'][$k]!=$vote->count){
                           $voteCount += (int)$_POST['voteCount'][$k]-$vote->count;
                       }
                       $vote->count = $_POST['voteCount'][$k];
                       $vote->update();
                   }
               }
           }
           if($voteCount!=0){
               $obj->countVote = (int)$obj->countVote+$voteCount;
           }
       }
       
       $bak = $article->update();
       if($bak)$bak = $obj->update();
       
       echo '<script>parent.showBack("'.$bak.'");</script>';
   }
   
   private function _Editsubmission($modelObj,$addfileds){
       foreach($addfileds as $key=>$value){
           if($value == 'date'){
               $modelObj->$key = strtotime($_POST[$key])-(8*3600);   
           }else{
              $modelObj->$key = $_POST[$key];   
           }
       }
      // return $modelObj;
   }
   private function _Editimglist($modelObj, $addfileds) {
        foreach ($addfileds as $key => $value) {

            if ($key != 'descriptionAll' && $key != 'descriptionAllMobi') {
                
                if (isset($_POST[$key]) && !empty($_POST[$key])) {
                    $inArr = explode(',', $_POST[$key]);
                    $str = '';
                    foreach ($inArr as $k => $valuea) {
                       
                        if (!empty($str))$str .= ',';
                        $title = isset($_POST[$key . 'title'][$k]) ? $_POST[$key . 'title'][$k] : '';
                        $str .= $valuea . '|' .$title ;
                    }
                    eval("\$modelObj->" . $key . " = \$str;");
                }else {
                    $modelObj->$key = '';
                }
            } else {
                if ($key == 'descriptionAll')
                    $modelObj->descriptionAll = (isset($_POST['infolistdes']) && !empty($_POST['infolistdes'])) ? implode(',', $_POST['infolistdes']) : '';
                if ($key == 'descriptionAllMobi')
                    $modelObj->descriptionAllMobi = (isset($_POST['infolistMobiledes']) && !empty($_POST['infolistMobiledes'])) ? implode(',', $_POST['infolistMobiledes']) : '';
            }
        }
       // return $modelObj;
    }
    public function actionDeleteOne($putArr = array()){
        if(!empty($putArr))$_POST = $putArr;
        if(empty($_POST['id']) || empty($_POST['wid'])){$this->redirect (array('site/error','msg'=>'参数错误，请与管理员联系！'));return;}
        $widget = Widget::model()->findByPk($_POST['wid']);
        $article = Article::model()->findByPk($_POST['id']);
        $addfileds = require_once 'addfileds_'.$widget->tableName.'.php';
        $imgPath = dirname(Yii::app()->getBasePath()).'/upload/'.$article->filetemp.'/';
        eval("\$obj = Add".$widget->tableName."::model()->findByPk(".$_POST['id'].");");
        if(!empty($article->litpic))if(is_file($imgPath.$article->litpic))unlink($imgPath.$article->litpic);
        if(!empty($article->Slitpic))if(is_file($imgPath.$article->Slitpic))unlink($imgPath.$article->Slitpic);
        if(is_array($addfileds)){
        foreach($addfileds as $key=>$value){
            if($value == 'upload' && !empty($obj->$key)){
                $arr = explode(',', $obj->$key);
                foreach($arr as $v){
                    if($key == 'infolist' || $key == 'infolistMobile'){
                        $arrEx = explode('|', $v);
                        if(is_file($imgPath.$arrEx[0]))unlink($imgPath.$arrEx[0]);
                    }else{
                        if(is_file($imgPath.$v))unlink($imgPath.$v);
                    }
                }
            }
            if($value == 'htmltext' && !empty($obj->$key)){
                preg_match_all('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i',$obj->$key,$match); 
                if(isset($match[2]) && !empty($match[2])){
                    if(is_array($match[2])){
                        foreach($match[2] as $val){
                            if(is_file(dirname(Yii::app()->getBasePath()).$val))unlink(dirname(Yii::app()->getBasePath()).$val);
                        }
                    }else{
                        if(is_file(dirname(Yii::app()->getBasePath()).$val))unlink(dirname(Yii::app()->getBasePath()).$val);
                    }
                }
            }
        }
        }
        $bak = $article->delete();
        if($bak)$bak = $obj->delete();
        echo $bak;
    }
    public function actionBatchAdd(){
        if(!isset($_GET['wid'])||empty($_GET['wid']))$this->redirect(array('listart/index'));
       $widget = Widget::model()->findByPk($_GET['wid']);
       if(!empty($widget->Attribute)){
           $attributeArr = explode(',', $widget->Attribute);
           if(count($attributeArr) > 1){
               $attribute = '';
               foreach($attributeArr as $value){
                   $attribute .= ',';
                   $attribute .= 'd.'.$value;
               }
           }else{
               $attribute = ',d.'.$attributeArr[0];
           }
       }
       $this->isSmallType = $_GET['channelId'];
       $addfileds = require_once 'addfileds_'.$widget->tableName.'.php';  
       $addCN = require_once 'addfiledsCn_'.$widget->tableName.'.php';
        $this->render('batchAdd',array(
           'channelId'=>$_GET['channelId'],
            'wid'=>$_GET['wid'],
           'attribute'=>$attributeArr,
           'addfileds'=>$addfileds,
           'modelName'=>$widget->tableName,
           'addCN'=>$addCN,
           'filetemp'=>date('Ymd')
       ));
    }
   public function actionBatchSave() {
        if (empty($_POST['modelName']) || empty($_POST['filetemp']) || empty($_POST['title'])) {
            $this->redirect(array('site/error', 'msg' => '参数错误，请与管理员联系！'));
            return;
        }
        $addfileds = require_once 'addfileds_' . $_POST['modelName'] . '.php';
        $topAll = adminSys::_getAllId($_POST['channelId']);
        foreach ($_POST['title'] as $key => $value) {
            $artObj = new Article();
            eval("\$addObj = new add" . $_POST['modelName'] . "();");
            $artObj->filetemp = $_POST['filetemp'];
            $artObj->channelId = $_POST['channelId'];
            $artObj->channelIdAll = $topAll;
            $artObj->wid = $_POST['wid'];
            $artObj->arcrank = $_POST['arcrank'];
            $artObj->senddate = time() - (8 * 3600);
            $artObj->ismobile = 1;
            $artObj->litpic = $_POST['litpic'][$key];
            $artObj->Slitpic = $_POST['litpic'][$key];
            $artObj->Awrite = 'admin';
            $artObj->click = rand(10,200);
            $artObj->ordering = !isset($_POST['ordering'][$key])||empty($_POST['ordering'][$key])?0:$_POST['ordering'][$key];
            $artObj->title = !isset($_POST['title'][$key])||empty($_POST['title'][$key])?'标题':$_POST['title'][$key];
            $artObj->save();
            $addObj->id = $artObj->id;
            $addObj->channelId = $_POST['channelId'];
            $addObj->userip = $_SERVER['REMOTE_ADDR'];
            foreach($addfileds as $k=>$val){
                $addObj->$k = !isset($_POST[$k][$key])?'':$_POST[$k][$key];
            }
            $addObj->save();
        }
        echo '<script>parent.backStaus();</script>';
    }
    public function actionDeleteall(){
        if(empty($_POST['numberArr'])){
            $this->redirect (array('site/error','msg'=>'参数错误，请与管理员联系！'));return;
            }
        $arrNum = json_decode($_POST['numberArr']);
        ob_start();
        foreach($arrNum as $value){
            $exarr = explode(',', $value);
            $this->actionDeleteOne(array('id'=>$exarr[0],'wid'=>$exarr[1]));
        }
        ob_end_clean();
        echo 1;
    }
    public function actionCheckAll(){
        if(empty($_POST['numberArr'])){
            echo '参数无效！';return;
            }
         $arrNum = json_decode($_POST['numberArr']);
         ob_start();
        foreach($arrNum as $value){
            $exarr = explode(',', $value);
            $this->actionCheckOne(array('id'=>$exarr[0]));
        }
        ob_end_clean();
        echo 1;
    }
    public function actionCheckOne($putArr = array()){
        if(!empty($putArr))$_POST = $putArr;
        if(empty($_POST['id'])){
            echo '无效参数！';
            return;
        }
        echo Article::model()->updateByPk($_POST['id'], array('arcrank'=>1));
    }
}
?>